<?php

namespace app\api\controller;

use app\admin\model\Member;
use app\api\service\Message as MessageService;

use think\Db;
use think\Exception;

class Message extends Base
{

    /**
     * 首页数据
     */
    public function home()
    {
        $param = self::getHttpParam();
        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '会员ID(memberId) 不能为空');
        }

        $memberId = $param->memberId;
        // 未读消息数
        $unreadMessages = MessageService::getUnreadMessages($memberId);
        // 最新一条活动推荐
        $messageActivity = $this->getNewestActivity(['a.member_id' => $memberId]);
        // 最新一条交易物流
        $messageLogistics = $this->getNewestLogistics(['member_id' => $memberId]);
        // 最新一条账号通知
        $messageNotice = $this->getNewestNotice(['member_id' => $memberId]);

        $data = [
            'messageActivity' => $messageActivity,
            'messageLogistics' => $messageLogistics,
            'messageNotice' => $messageNotice,
            'unreadMessages' => $unreadMessages,
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    // 最新一条活动推荐
    protected function getNewestActivity($where)
    {
        $model = db('message_activity');
        //$where['a.is_read'] = 0;
        $field = 'a.id, b.create_date, b.name as title';
        $list = $model->alias('a')->where($where)->join('__ACTIVITY__ b', 'a.activity_id = b.id')->field($field)->order('b.create_date DESC')->find();
        if (!$list) {
            return '';
        }

        return $list;
    }

    // 最新一条交易物流
    protected function getNewestLogistics($where)
    {
        $model = db('message_logistics');
        //$where['is_read'] = 0;
        $field = 'id, create_date, title';
        $list = $model->where($where)->field($field)->order('create_date DESC')->find();
        if (!$list) {
            return '';
        }

        return $list;
    }

    // 最新一条账号通知
    protected function getNewestNotice($where)
    {
        $model = db('message_notice');
        //$where['is_read'] = 0;
        $field = 'id, create_date, title';
        $list = $model->where($where)->field($field)->order('create_date DESC')->find();
        if (!$list) {
            return '';
        }

        return $list;
    }
}